package com.org.khtn.command.update;

import java.util.Map;
import java.util.Vector;

import com.org.khtn.command.MyQuery;
import com.org.khtn.data.Data;
import com.org.khtn.data.DataTables;
import com.org.khtn.data.Table;
import com.org.khtn.ultilities.Ultilities;

public class UpdateQuery extends MyQuery {
	final String className = getClass().getSimpleName() + ":";
	Map<String, String> tableDefine;

	public UpdateQuery(String Query, String databaseName) {
		dt = new DataTables(new Data(databaseName, "sadsa", "mytest\\data\\"));
		query = Query;
		parse = new ParseUpdate(Query);
		table = dt.getAllTableName();

	}

	public boolean fieldsExist(String[] fields) {
		int length = fields.length;
		for (int i = 0; i < length; i++)

		{
			if (!tableDefine.containsKey(fields[i]))
				return false;
		}
		return true;
	}

	/**
	 * thực thi truy vấn
	 */
	@Override
	public int executeNonQuery() {
		// TODO Auto-generated method stub
		final String methodName = "executeNonQuery():";
		System.out.println(className + methodName + "vao 1");

		if (!parse.eval())
			return -10;
		else
			key = parse.parse();

		if (!tableExist(key[0]))
			return -11;
		tableDefine = dt.getTableDefines(key[0]);

		System.out.println(className + methodName + "key[1]: " + key[1]);
		System.out.println(className + methodName + "key[2]: " + key[2]);

		Table myTable = dt.getTable(key[0]);
		Vector rowID = Ultilities.filterByWhereCondition(myTable, key[2], dt);
		String[] temp = key[1].split("\\s*,\\s*");
		int length = temp.length;
		int rowLenght = rowID.size();
		if (rowID.size() > 0) {
			for (int i = 0; i < length; i++) {
				String[] temp1 = temp[i].split("=");
				if (!fieldsExist(new String[] { temp1[0] }))
					return -12;
				String type = tableDefine.get(temp1[0]);
				int lengthValue = temp1[1].length();
				System.out.println(className + methodName
						+ "temp1[1].charAt(0):" + temp1[1].charAt(0));

				if (temp1[1].charAt(0) == 39
						&& temp1[1].charAt(lengthValue - 1) == 39) {
					temp1[1] = temp1[1].substring(1, lengthValue - 1);
					System.out.println(className + methodName + "temp1[1]:"
							+ temp1[1]);

					if (type.equalsIgnoreCase("int")) {
						try {
							Integer.parseInt(temp1[1]);
						} catch (NumberFormatException nf) {
							return -13;
						}
					}

				}

				for (int j = 0; j < rowLenght; j++) {
					int numRow = Integer.parseInt(rowID.get(j).toString());
					dt.editRecord(numRow, key[0], temp1[0], temp1[1]);
				}

			}
		}
		System.out.println(rowID);
		return rowLenght;
	}

	// public static void main(String[] args) {
	// UpdateQuery uq = new UpdateQuery(
	// "update sach set name='son wa dep' where 'aaa'=masach or masach='12'",
	// "qlhs");
	// uq.executeNonQuery();
	// }
}
